package cc.rengu.redp.system.service.impl;

import cc.rengu.redp.common.utils.RedpUtil;
import cc.rengu.redp.system.dao.CommonUserMessageMapper;
import cc.rengu.redp.system.domain.User;
import cc.rengu.redp.system.domain.UserMessage;
import cc.rengu.redp.system.service.CommonUserMessageService;
import cc.rengu.redp.system.service.CommonUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author System
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class CommonUserMessageServiceImpl extends ServiceImpl<CommonUserMessageMapper, UserMessage> implements CommonUserMessageService {

    @Autowired
    private CommonUserService commonUserService;

    @Override
    public void sendMessage(String userName, String message, String sourceType, String sourceDesc) {
        User user = commonUserService.findByName(userName);
        UserMessage userMessage = new UserMessage();
        userMessage.setUserId(user.getUserId());
        userMessage.setMessage(message);
        userMessage.setReadFlg(false);
        userMessage.setSourceType(sourceType);
        if (UserMessage.SOURCE_TYPE_USER.equals(sourceType) && StringUtils.isBlank(sourceDesc)) {
            userMessage.setSourceDesc(RedpUtil.getCurrentUser().getUsername());
        } else {
            userMessage.setSourceDesc(sourceDesc);
        }
        userMessage.setCreateTime(LocalDateTime.now().toString());
        this.baseMapper.insert(userMessage);
    }
}
